import Pagination from '@/pages/pc/components/Pagination';
import { WorksItem } from '@/pages/pc/components/Works';
import { useState, useEffect, Children, useRef } from 'react';
import classNames from 'classnames';
import CourseDetail from '@/pages/pc/components/NewCourseDetail';
import PackageC from '@/pages/pc/components/Package';
import { RewardSuccess, InvitedReward } from '@/pages/pc/components/Reward';
import { Popover, Tabs } from 'antd';
import styles from './index.less';
import { allGet } from '@/services/pc';
import VideoPlayerModal from '../../components/VideoPlayer';
import useBuy from '@/hooks/useBuy';
import { Helmet, Link, history, useModel, useLocation } from 'umi';
import storage from '@/utils/storage';
import { INVITED_REWARD_CLASSIDS } from '@/common/const';
import Empty from '../../components/Empty';
import moment from 'moment';
import { formatDateBeForeZeroPoint } from '@/utils';
import ZModal from '../../components/ZModal';
const { TabPane } = Tabs;

// 套餐搭配
const Package = (props) => {
  const [data] = useState(props.data);
  if (!data) return null;
  const newData =
    data?.map((item) => ({
      ...item,
      courses: Object.values(item.courses) || [],
    })) || [];
  return (
    <section className={styles.package}>
      <img
        className={styles.title}
        src={require('@/assets/pc/images/course/tc-title.png')}
        alt=""
      />
      <div className={styles.body}>
        <PackageC data={newData} itemKey="sid" />
      </div>
    </section>
  );
};

// 课程介绍
const Introduce = ({ data }) => {
  const { messages = [] } = data;

  return (
    <div className={styles.introduce}>
      {data.message && (
        <div className={styles.message} dangerouslySetInnerHTML={{ __html: data.message }} />
      )}
      {/* {messages?.map((item) => {
        const isImg = item?.isimage == 1;
        if (isImg) {
          return (
            <div key={item.aid} className={styles.introduceItem}>
              <img loading="lazy" src={item.pic} alt="" />
            </div>
          );
        }
        return (
          <video
            key={item?.aid}
            className={styles.video}
            controls
            controlsList="nodownload"
            disablePictureInPicture
            preload="metadata"
            src={item?.attachment}
          >
            <p>您的浏览器不支持html5播放器，请更换浏览器进行尝试</p>
          </video>
        );
        return null;
      })} */}
    </div>
  );
};

interface CatalogueItemProps {
  /**
   * -1 免费试学
   * 0 购买后观看
   * 1 追加课（DLC课时）
   */
  type: -1 | 0 | 1;
  title?: string;
  index?: number;
  detail: any;
  lid: any;
}
const CatalogueItem: React.FC<CatalogueItemProps> = ({
  type,
  title,
  index,
  detail = {},
  ...props
}) => {
  //单个课购买订单弹窗
  const { courseBuy } = useBuy();
  const handleClick = () => {
    if (type === 1 || type === -1) {
      return window.open(`/center/video/player/${detail.classid}?lid=${props.lid}`);
    }
    if (detail.payed === true) {
      return window.open(`/center/video/player/${detail.classid}?lid=${props.lid}`);
    }

    courseBuy({
      classid: detail.classid,
      mentor: new URLSearchParams(window.location.search).get('mentor'),
    } as any);
  };
  return (
    <div className={classNames(styles.item, styles[`type${type}`])} onClick={handleClick}>
      <div className={styles.left}>
        <span className={styles.index}>{index}.</span>
        <i className={styles.play} />
        <span className={styles.title}>{title}</span>
      </div>

      <div className={styles.right}>
        {type == -1 && <div className={styles.sxbutton}>免费试学</div>}
        {type == 0 && (
          <>
            <div className={styles.gmbutton}>{detail.payed === true ? '观看课程' : '购买观看'}</div>
          </>
        )}
        {type == 1 && <i className={styles.lock} />}
      </div>
    </div>
  );
};

const CollapsibleItem = ({ data, hideHeader = false, detail = {}, index }) => {
  const [collapsed, setCollapsed] = useState(false);
  if (!data?.children || data?.children?.length <= 0) return null;
  return (
    <div className={classNames(styles.collapsibleItem, { [styles.collapsed]: collapsed })}>
      <div
        className={styles.header}
        style={hideHeader ? { display: 'none' } : {}}
        // onClick={() => setCollapsed(!collapsed)}
      >
        {`第${index + 1}章`} &nbsp;&nbsp;{data.header}
        <i className={styles.arrow} />
      </div>
      <div className={styles.body}>
        {data?.children?.map((item, index) => {
          if (item._index === undefined) {
            item._index = catalogueItemIndex++;
          }
          return <CatalogueItem key={item.title} index={item._index} {...item} detail={detail} />;
        })}
      </div>
    </div>
  );
};

let catalogueItemIndex = 1;
// 课程目录
const Catalogue = (props) => {
  const transformData = (data = [] as any[]) => {
    const hasC = data.some((item) => item.cid != 0 && item.children && item.children.length > 0);
    const newData: any[] = [...data];
    const mf: any = {
      header: '试听课',
      children: [],
    };
    const dlc: any = {
      header: '追加课（DLC课时）',
      children: [],
    };
    newData.forEach((item: any, index) => {
      newData[index] = {
        ...item,
        header: item.name,
      };
      const children = item.children;
      if (children && Array.isArray(children)) {
        children.forEach((item, index) => {
          const newItem = {
            ...item,
            title: item.name,
          };
          children[index] = newItem;
          // if (item.type == -1) {
          //   mf.children.push(newItem)
          //   children[index].delete = true;
          // }
          // if (item.type == 1) {
          //   dlc.children.push(newItem);
          //   children[index].delete = true;
          // }
        });
        newData[index].children = children.filter((item) => item && item.delete !== true);
      }
    });
    const othersIndex = newData.findIndex((item) => item.cid == 0);
    if (othersIndex > -1) {
      newData[othersIndex].header = '其他课时';
      newData[othersIndex].header = hasC ? '其他课时' : '课程视频';
      // if (dlc.children.length > 0) {
      //   newData.splice(othersIndex, 0, dlc);
      // }
    }

    if (mf.children.length > 0) {
      newData.unshift(mf);
    }
    return newData.filter((item) => Array.isArray(item.children) && item.children.length > 0);
  };
  const data = transformData(props.data);
  // const data = [
  //   {
  //     header: '试听课',
  //     children: [{ type: 1, title: 'Blender能做什么？' }]
  //   },
  //   {
  //     header: '第一章 对软件的整体认识和界面的讲解',
  //     children: [{ type: 2, title: 'Blender能做什么？' }, { type: 2, title: '进阶案例：机械设计建模' }, { type: 2, title: '吉祥物建模' }, { type: 2, title: 'Blender能做什么2？' },]
  //   },
  //   {
  //     header: '追加课（DLC课时）',
  //     children: [{ type: 3, title: '进阶案例：场景的设计与建模' }, { type: 3, title: '进阶案例：吉祥物IP的建模与商业计划书' }, { type: 3, title: '进阶案例：机械设计建模' },]
  //   },
  // ]
  catalogueItemIndex = 1;
  return (
    <div className={styles.catalogue}>
      {data.map((item, index) => {
        return (
          <CollapsibleItem
            key={item.cid}
            data={item}
            index={index}
            hideHeader={data.length <= 1}
            detail={props.detail}
          />
        );
      })}
    </div>
  );
};

const Works = ({ classId }) => {
  const [data, setData] = useState<any>({});
  const [current, setCurrent] = useState(1);
  const pageSize = 25;
  const handleClick = (index, e) => {
    VideoPlayerModal.showStar({
      data: data?.data?.list?.map?.((item) => ({ ...item, url: item.video || item.pic })) || [],
      defaultIndex: index,
    });
  };
  const handlePageChange = (page) => {
    setCurrent(page);
  };
  const init = async () => {
    const response = await allGet({
      params: {
        mod: 'busywork',
        do: 'list',
        classid: classId,
        page: current,
        perpage: pageSize,
        version: 'pc1.0',
      },
    });
    setData(response);
  };
  useEffect(() => {
    init();
  }, [current]);
  return (
    <div className={styles.works}>
      <div className={styles.list}>
        {data?.data?.list?.length > 0 ? (
          data?.data?.list?.map((item, index) => (
            <div onClick={(e) => handleClick(index, e)} key={item.bid} className={styles.item}>
              {' '}
              <WorksItem index={index} type={item.video ? 'video' : 'img'} {...item} itemType={2} />
            </div>
          ))
        ) : (
          <Empty style={{ margin: '50px auto' }} />
        )}
      </div>
      {data?.data?.count > pageSize && (
        <Pagination
          pageSize={pageSize}
          className={styles.pagination}
          total={data?.data?.count}
          current={current}
          onChange={handlePageChange}
        />
      )}
    </div>
  );
};

const MyTabs = (props) => {
  const { chapters = [] } = props?.data || {};
  const handleTabChange = () => {
    const dom = document.getElementById('courses-detail-tabs');
    // 滚动到目标 div
    dom?.scrollIntoView({ behavior: 'smooth' });
    console.log(dom);
  };

  const navScrollCurrent = useRef(0);
  const navCurrent = useRef<any>(null);
  const scroll = () => {
    const nav = document.querySelector('#detail-tab .ant-tabs-nav') as any;
    navCurrent.current = nav;
    const navOffsetTop = nav.offsetTop;
    navScrollCurrent.current = navOffsetTop;
  };

  const addScrollLitesner = () => {
    // 获取当前滚动位置
    const scrollPosition = window.scrollY || window.pageYOffset;

    // 检查是否滚动到了导航栏的原始位置
    if (scrollPosition >= navScrollCurrent.current + 68 + 80) {
      navCurrent.current.classList.add('fixed');
    } else {
      navCurrent.current.classList.remove('fixed');
    }
    console.log(scrollPosition);
  };
  useEffect(() => {
    scroll();
    // 添加滚动事件监听器
    window.addEventListener('scroll', addScrollLitesner);
    return () => {
      // 清除滚动事件监听器
      window.removeEventListener('scroll', addScrollLitesner);
    };
  }, []);

  return (
    <div className={styles.tabWrapper} id="courses-detail-tabs">
      <Tabs className={styles.tabs} defaultActiveKey="1" onChange={handleTabChange} id="detail-tab">
        <TabPane tab="课程介绍" key="1">
          <Introduce data={props.data} />
        </TabPane>
        <TabPane tab="课程目录" key="2">
          <Catalogue data={chapters} detail={props?.data} />
        </TabPane>
        {/* {props?.query?.type !== 'preview' && (
          <TabPane tab="学员作业" key="3">
            <Works classId={props.classId} />
          </TabPane>
        )} */}
      </Tabs>
    </div>
  );
};

const Index = (props) => {
  const location = useLocation();
  const { match, query } = props;

  const { id: classId } = match?.params || {};

  const searchParams = new URLSearchParams(location.search);
  const mentorParam = searchParams.get('mentor');
  // 邀请成功奖励弹窗
  const [rewardSuccessVisiable, setRewardSuccessVisiable] = useState(true);

  // 被邀请者奖励弹窗
  const [invitedRewardVisiable, setInvitedRewardVisiable] = useState(false);

  //单个课购买订单弹窗
  const { courseBuy } = useBuy();
  const handleBuy = () => {
    courseBuy({
      classid: classId,
      mentor: mentorParam, // 加入 mentor 参数
    } as any);
  };

  const [detail, setDetail] = useState<any>(props.detail || {});
  const [clientOk, setClientOk] = useState(false);
  const getDetail = async () => {
    const response =
      query?.type !== 'preview'
        ? await allGet({
            params: {
              mod: 'course',
              do: 'detail',
              classid: classId,
              shareuid: query?.shareuid,
              sharelid: query?.sharelid,
              fromuid: query?.fromuid,
              mentor: mentorParam,
              version: 'pc1.0',
            },
          })
        : await allGet({
            params: { mod: 'course', do: 'preview', sid: classId, version: 'pc1.0' },
          });
    if (response.success && response.data) {
      setDetail(response.data || {});
      setClientOk(true);
    }
  };
  useEffect(() => {
    // 这里还得再调用一次，获取登录和token相关的数据
    getDetail();
  }, [classId]);

  useEffect(() => {
    isShowInvitedReward();
  }, []);

  // 被邀请者弹窗领取优惠券
  const isShowInvitedReward = () => {
    const invitedRewardClassids = storage.get(INVITED_REWARD_CLASSIDS);
    console.log(invitedRewardClassids, 'invitedRewardClassids');
    // 分享过来的用户id存在，然后不存在领取过的课程id
    if (query?.fromuid && !invitedRewardClassids[classId]) {
      setInvitedRewardVisiable(true);
    }
  };

  const courseDetailType = () => {
    /**
     * 1 秒杀
     * 2 预售
     * 3 正常
     */
    if (detail?.bookprice > 0 && moment(detail?.bookdead, 'X').isSameOrAfter(moment())) {
      return 2;
    }
    if (detail.secskills?.secskillprice) {
      return 1;
    }
    if (detail.type == 8) {
      return 2;
    }
    return 3;
  };
  const hasRewrad = !!detail.invitebuys;

  const handleEditClass = () => {
    history.push(`/center/upload-courses?classid=${detail.classid}`);
    // window.open(`/center/upload-courses?classid=${detail.classid}`);
  };
  const [left, setLeft] = useState(99999);
  const cLeft = () => {
    const innerWidth = window.innerWidth;
    if (innerWidth <= 1220 + 70 + 15) {
      setLeft(1220 + 70 + 15);
    } else {
      setLeft((innerWidth - 1220) / 2 + 1220 + 15);
    }
  };
  useEffect(() => {
    cLeft();
    window.addEventListener('resize', cLeft);
    return () => {
      window.removeEventListener('resize', cLeft);
    };
  }, []);

  // 是否有优惠券的分享
  const hasYhqShare = () => {
    // 秒杀没有优惠券
    if (courseDetailType() === 1) return false;
    if (detail?.coupons?.sharecouponamount && detail?.coupons?.sharecoupondead) {
      const sharecoupondead = formatDateBeForeZeroPoint(detail?.coupons?.sharecoupondead * 1000);
      if (moment().isBefore(moment(sharecoupondead))) {
        return true;
      }
    }
    return false;
  };
  return (
    <>
      <div className={classNames(styles.page, styles[props?.query?.type])}>
        {/* <div className={styles.bg} />
        <div className={styles.bg2} /> */}
        <div className={styles.bgwrapper}>
          <div className={styles.picbg} style={{ backgroundImage: `url(${detail?.pic})` }} />
          <div className={styles.leftmask} />
          <div className={styles.topmask} />
          <div className={styles.bottommask} />
          <div className={styles.allmask} />
          {/* <div className={styles.picbg2} /> */}
        </div>
        <div className={styles.content}>
          <div className={styles.w1200}>
            <div className={styles.path}>
              <Link className={styles.all} to={'/courses/1?order=classid&sid=-9999&cid=-9999'}>
                全部课程
              </Link>
              <span className={styles.arrow}>{'>'}</span>
              <span className={styles.current}>{detail?.name}</span>
            </div>
            <Helmet>
              <title>{detail?.title || detail.name}</title>
              <meta name="title" content={detail.title || detail.name} />
              {detail?.keywords && <meta name="keywords" content={detail.keywords} />}
              {detail?.description && <meta name="description" content={detail.description} />}
            </Helmet>
            {props.initialPropsOk && (
              <>
                <div className={styles.detail}>
                  <CourseDetail
                    data={detail}
                    needClient={true}
                    clientOk={clientOk}
                    type={courseDetailType()}
                    role={1}
                    onBuy={handleBuy}
                    classId={classId}
                    query={query}
                    hasRewrad={hasRewrad}
                    onLike={getDetail}
                    zpnumRealTime={query?.type !== 'preview'}
                    isPreview={query?.type === 'preview'}
                  />
                </div>
              </>
            )}
          </div>
          <MyTabs classId={classId} data={detail} query={query} />
          {/* <RewardSuccess visible={rewardSuccessVisiable} money={detail?.invitebuys?.reduce} name={detail?.name} onClose={() => { setRewardSuccessVisiable(false) }} /> */}

          <InvitedReward
            num={detail?.invitebuys?.reduce}
            fromuid={query?.fromuid}
            classId={classId}
            visible={invitedRewardVisiable}
            onClose={() => {
              setInvitedRewardVisiable(false);
            }}
          />
        </div>
      </div>
      <div className={styles.floatButts} style={{ left: `${left}px` }}>
        <div className={styles.buttons}>
          {detail?.edit === 1 && (
            <div className={styles.button} onClick={handleEditClass}>
              <i className={classNames(styles.icon, styles.icon1)} />
              <span className={styles.text}>编辑课程</span>
            </div>
          )}
          {hasYhqShare() ? (
            <Popover
              overlayClassName={styles.sharepopover2}
              placement="leftBottom"
              trigger="hover"
              content={<Wxshare2 classId={classId} num={detail?.coupons?.sharecouponamount} />}
              title={() => null}
            >
              <div className={styles.button}>
                <i className={classNames(styles.icon, styles.icon2)} />
                <span className={styles.text}>分享课程</span>
              </div>
            </Popover>
          ) : (
            <Popover
              overlayClassName={styles.sharepopover}
              placement="left"
              trigger="hover"
              content={<Wxshare classId={classId} />}
              title={() => null}
            >
              <div className={styles.button}>
                <i className={classNames(styles.icon, styles.icon2)} />
                <span className={styles.text}>分享课程</span>
              </div>
            </Popover>
          )}
          <div className={styles.button} onClick={() => ZModal.showDownloadPlayer()}>
            <i className={classNames(styles.icon, styles.icon4)} />
            <span className={styles.text}>播放器下载</span>
          </div>
          <div className={styles.button} onClick={() => history.push('/learning')}>
            <i className={classNames(styles.icon, styles.icon5)} />
            <span className={styles.text}>学习中心</span>
          </div>
          <Popover
            overlayClassName={styles.kefupopover}
            placement="left"
            trigger="hover"
            content={<WxKefu classId={classId} />}
            title={() => null}
          >
            <div className={styles.button}>
              <i className={classNames(styles.icon, styles.icon6)} />
              <span className={styles.text}>客服</span>
            </div>
          </Popover>
          {/* <div className={styles.button} onClick={() => window.open('/contract')}>
            <i className={classNames(styles.icon, styles.icon3)} />
            <span className={styles.text}>课程合同</span>
          </div> */}
        </div>
        <div
          className={styles.top}
          onClick={() =>
            window.scrollTo({
              left: 0,
              top: 0,
            })
          }
        >
          <i className={styles.iconTop} />
        </div>
      </div>
    </>
  );
};
Index.getInitialProps = async ({ match, history }) => {
  const { path, params } = match;
  const { query, search } = history?.location || {};
  const { id } = params;
  const searchParams = new URLSearchParams(search);
  const [detail] = await Promise.all([
    query.type !== 'preview'
      ? allGet({
          params: {
            mod: 'course',
            do: 'detail',
            mentor: searchParams.get('mentor'),
            classid: id,
            version: 'pc1.0',
          },
        })
      : allGet({ params: { mod: 'course', do: 'preview', sid: id, version: 'pc1.0' } }),
  ]);
  return {
    path,
    classId: id,
    query: {
      ...query,
      mentor: searchParams.get('mentor'), // 确保mentor包含在query对象中
    },
    detail: detail?.data || {},
    initialPropsOk: true,
  };
};
export default Index;

const Wxshare = (props) => {
  const { userInfo } = useModel('user');
  let url = `${location.origin}/center/courses/detail/${props.classId}`;
  if (userInfo.uid) {
    url = `${url}?shareuid=${userInfo.uid}`;
  }
  console.log(url);
  const img = `https://www.cgjoy.com/app.php?mod=train&do=qrcode&version=pc1.0&url=${encodeURIComponent(
    url,
  )}`;
  return (
    <div className={styles.wxsharemain}>
      <img loading="lazy" src={img} width="134" height="134" alt="" />
      <div className={styles.title}>
        <img
          loading="lazy"
          src={require('../../components/CourseDetail/images/icon-wx.png')}
          alt=""
          width="19"
        />
        微信扫码分享
      </div>
    </div>
  );
};

// 遍历时间范围，判断当前时间在哪个范围内
function getCurrentTimeIndex() {
  const times = ['9:00 - 22:00'];
  const now = moment();
  for (let i = 0; i < times.length; i++) {
    const [start, end] = times[i].split(' - ');
    const startTime = moment(start, 'HH:mm');
    const endTime = moment(end, 'HH:mm');
    // 判断当前时间是否在范围内
    if (now.isBetween(startTime, endTime, null, '[)')) {
      return i;
    }
  }
  return -1; // 如果不在任何范围内，返回 -1
}

const WxKefu = (props) => {
  const index = getCurrentTimeIndex();
  console.log(index, 'index');
  return (
    <div className={styles.kefumain}>
      <div className={styles.title}>微信扫码添加客服</div>
      <div className={styles.body}>
        <div className={classNames(styles.item, index === 0 ? styles.actived : '')}>
          <img
            loading="lazy"
            src={require('@/assets/pc/images/course/kefu3.png')}
            width="120"
            height="120"
            alt=""
          />
          <div className={styles.des}>
            <div className={styles.dot} />
            <div className={styles.text}>{index === 0 ? '在线' : '离线'}</div>
            <div className={styles.line} />
            <div className={styles.time}>9:00 - 22:00</div>
          </div>
        </div>
      </div>
    </div>
  );
};

const Wxshare2 = (props) => {
  const { userInfo } = useModel('user');
  let url = `${location.origin}/center/courses/detail/${props.classId}`;
  if (userInfo.uid) {
    url = `${url}?shareuid=${userInfo.uid}`;
  }
  console.log(url);
  const img = `https://www.cgjoy.com/app.php?mod=train&do=qrcode&version=pc1.0&url=${encodeURIComponent(
    url,
  )}`;
  return (
    <div className={styles.wxsharemain2}>
      <div className={styles.tips}>分享得优惠券活动</div>
      <div className={styles.price}>
        {props.num} <i className={styles.unit}>¥</i>
      </div>
      <img loading="lazy" src={img} width="75" height="75" alt="" />
      <div className={styles.title}>
        <img
          className={styles.icon}
          src={require('../../components/CourseDetail/images/icon-wx.png')}
          alt=""
        />
        微信扫码分享
      </div>
      <div className={styles.tips2}>分享后截图给[人工客服]领取优惠券</div>
    </div>
  );
};
